<template>
  <app-section :loading="pageLoading">
    <van-nav-bar
      title="选择用户"
      @click-left="backRoute"
      @click-right="saveSelected"
      left-arrow
      left-text="返回"
      right-text="确定">
    </van-nav-bar>
    <van-cell-group>
      <van-field
        clearable
        v-model="keyword"
        right-icon="search"
        placeholder="请输入关键字查询用户"
        @click-right-icon="onRefresh"
        @input="searchByKeyword">
      </van-field>
    </van-cell-group>
    <van-pull-refresh v-model="pullLoading" @refresh="onRefresh">
      <van-checkbox-group v-model="selectedList">
        <van-list
          v-model="listLoading"
          :finished="listFinished"
          :finished-text="finishedText"
          :error.sync="listError"
          error-text="请求失败，点击重新加载"
          @load="onLoad()">

          <van-cell
            clickable
            v-for="(item,index) in userList"
            :key="index"
            :title="item.bpmBizTitle"
            @click="toggleChecked(index)">
            <van-checkbox
              ref="userCheckBox"
              slot="icon"
              shape="square"
              :name="item"
            >
            </van-checkbox>
            <div style="position: relative;margin-left:0.5rem">
              <div>
                <img :src="item.avatar" style="width: 2.5rem;height: 2.5rem;border-radius: 50%;"/>
              </div>
              <div style="position: absolute;top:0;left:3.2rem">
                <div style="font-size: 1rem;line-height: 1rem;">{{ item.realname }}</div>
                <div style="font-size: 0.9rem;line-height: 0.9rem;margin-top: 0.5rem;">{{ item.username }}</div>
              </div>
            </div>
          </van-cell>

        </van-list>
      </van-checkbox-group>
    </van-pull-refresh>
  </app-section>
</template>

<script>
  import AppSection from '@/components/AppSection'
  import { getAction,getFileAccessHttpUrl } from '@/api'
  import debounce from 'lodash/debounce';
  import { downloadAbled } from '@/util/util'

  export default {
    name: 'SelectUsers',
    props:{
      syncFlow:{
        type: Boolean,
        default: false,
        required: false
      }
    },
    components:{
      AppSection
    },
    data(){
      this.searchByKeyword = debounce(this.searchByKeyword, 1000);//消抖
      return {
        pageLoading:false,
        pullLoading: false,
        listLoading: false,
        listFinished:false,
        finishedText:'没有更多了',
        listError:false,
        pageNo:1,
        pageSize:10,
        url:"/sys/user/appUserList",
        userList:[],
        selectedList:[],
        keyword:'',
        destination:'',
        users:''
      }
    },
    methods:{
      backRoute(){
        this.$emit("back")
      },
      saveSelected(){
        let arr = this.backUserfulData()
        if(arr && arr.length>1 && this.destination==0){
          this.$toast("委托人只能选择一个")
          return
        }
        this.$emit("ok",arr,this.destination)
      },
      searchByKeyword(){
        this.onRefresh()
      },
      loadItemByUsername(username){
        return new Promise((resolve,reject) => {
          getAction(this.url,{username:username}).then(res=>{
            if(res.success){
              resolve(res.result.records[0])
            }else{
              reject();
            }
          }).catch(()=>{
            reject();
          })
        })
      },
      onRefresh() {
        this.pullLoading = true
        this.pageNo = 1
        let sf = this.syncFlow === true?'1':'';
        let param = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          keyword:this.keyword,
          syncFlow:sf
        }
        this.userList=[]
        getAction(this.url,param).then(res=>{
          console.log("onRefresh",res);
          this.pullLoading = false
          if(res.success){
            this.pageNo++
            let arr = res.result.records
            for(let item of arr){
              this.avatarHandler(item)
              this.userList.push(item)
            }
          }
        })
      },
      onLoad(){
        this.listLoading = true;
        let param = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          keyword:this.keyword
        }
        getAction(this.url,param).then(res=>{
          this.listLoading = false;
          if(res.success){
            // this.$toast.success("加载完成");
            this.pageNo++
            let arr = res.result.records
            for(let item of arr){
              this.avatarHandler(item)
              this.userList.push(item)
            }
            let selectArr=arr.filter(item=>this.users.indexOf(item.username)!=-1);
            this.selectedList=selectArr;
            if(!arr || arr.length<this.pageSize){
              console.log("加载完成!")
              this.listFinished = true;
            }
            console.log("结果数据", this.userList)
          }else{
            this.error = true;
          }
        }).catch(e=>{
          console.log("请求错误",e)
          this.error = true;
        })
      },

      toggleChecked(index){
        this.$refs.userCheckBox[index].toggle();
      },
      clearAll(flag){
        /**
         * flag 状态值
         * 0 委托人
         * 1 下一步的操作人
         * 2 抄送人
         */
        this.destination = flag
        this.selectedList=[]

      },
      selectUser(users){
        //默认选中人员
        console.log(users)
        this.users = users
      },
      avatarHandler(item){
        let avatar = item.avatar
        if(avatar){
          let url = getFileAccessHttpUrl(avatar);
          downloadAbled(url).then(()=>{
            console.log(1)
            item.avatar = url
          }).catch(()=>{
            if(item.sex=='2'){
              item.avatar = 'static/mobile/img/common/48/avatar_girl.png';
            }else{
              item.avatar = 'static/mobile/img/common/48/avatar_boy.png';
            }
          })
        }else{
          if(item.sex=='2'){
            item.avatar = 'static/mobile/img/common/48/avatar_girl.png';
          }else{
            item.avatar = 'static/mobile/img/common/48/avatar_boy.png';
          }
        }

      },
      backUserfulData(){
        let arr = []
        for(let item of this.selectedList){
          let obj = {
            username:item.username,
            realname:item.realname,
            id:item.id,
            avatar:item.avatar
          }
          arr.push(obj)
        }
        return arr;

      }

    }
  }
</script>

<style scoped>

</style>